package com.nai365.nart.member.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nai365.nart.common.core.constant.SecurityConstants;
import com.nai365.nart.common.core.util.R;
import com.nai365.nart.common.core.vo.WalletChangeVo;
import com.nai365.nart.common.log.annotation.SysLog;
import com.nai365.nart.common.security.annotation.Inner;
import com.nai365.nart.common.security.util.SecurityUtils;
import com.nai365.nart.member.entity.Member;
import com.nai365.nart.member.entity.Wallet;
import com.nai365.nart.member.entity.WalletChange;
import com.nai365.nart.member.service.MemberService;
import com.nai365.nart.member.service.WalletChangeService;
import com.nai365.nart.member.service.WalletService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * 钱包表
 *
 * @author baogs
 * @date 2021-05-12 14:33:31
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/wallet" )
@Api(value = "wallet", tags = "钱包表管理")
public class WalletController {

	private final WalletService walletService;
	private final WalletChangeService walletChangeService;

	/**
	 * 分页查询
	 * @param page 分页对象
	 * @param wallet 钱包表
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page" )
	public R getWalletPage(Page page, Wallet wallet) {
		List<OrderItem> orderItemList = new ArrayList<OrderItem>();
		OrderItem orderItem = new OrderItem();
		orderItem.setAsc(false);
		orderItem.setColumn("update_time");
		orderItemList.add(orderItem);
		page.setOrders(orderItemList);
		return R.ok(walletService.page(page, Wrappers.query(wallet)));
	}






	/**
	 * 通过id查询钱包表
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}" )
	public R getById(@PathVariable("id" ) Long id) {
		Wallet wallet = walletService.getWallet(id);
		BigDecimal freezeNart = wallet.getFreezeNart();
		BigDecimal yhdBalance = wallet.getNartBalance();
		wallet.setNartBalance(yhdBalance.subtract(freezeNart));
		return R.ok(wallet);
	}


	/**
	 * 通过id查询钱包表
	 * @param userId
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/getById_inner" )
	@Inner
	public R getByIdInner(@RequestParam(name = "userId",required = true) Long userId) {
		return walletService.getWalletInner(userId);
	}



	/**
	 * 新增钱包表
	 * @param wallet 钱包表
	 * @return R
	 */
	@ApiOperation(value = "新增钱包表", notes = "新增钱包表")
	@SysLog("新增钱包表" )
	@PostMapping("/save")
	// TODO
	public R save(@RequestBody Wallet wallet) {
		return R.ok(walletService.save(wallet));
	}

	/**
	 * 修改钱包表
	 * @param wallet 钱包表
	 * @return R
	 */
	@ApiOperation(value = "修改钱包表", notes = "修改钱包表")
	@SysLog("修改钱包表" )
	@PutMapping
	public R updateById(@RequestBody Wallet wallet) {
		wallet.setType(0);

		if ((wallet.getNewRmbBalance() == null || wallet.getNewRmbBalance().compareTo(BigDecimal.ZERO) == 0)
				&& (wallet.getNewNartBalance() == null || wallet.getNewNartBalance().compareTo(BigDecimal.ZERO) == 0)){
			wallet.setNewNartBalance(wallet.getNartValue());
			wallet.setNewRmbBalance(wallet.getRmbValue());
			wallet.setOperateBy((long)SecurityUtils.getUser().getId());
			wallet.setUpdateTime(null);
			return R.ok(walletService.updateById(wallet),"修改成功");
		}else{
			wallet.setNewNartBalance(wallet.getNartValue());
			wallet.setNewRmbBalance(wallet.getRmbValue());
			wallet.setOperateBy((long)SecurityUtils.getUser().getId());
			wallet.setUpdateTime(null);
			return R.ok(walletService.updateById(wallet),"上一次的修改值已被覆盖");
		}

	}
	/**
	 * 修改钱包表
	 * @param wallet 钱包表
	 * @return R
	 */
	@ApiOperation(value = "冻结nart", notes = "修改钱包表")
	@SysLog("修改钱包表" )
	@PostMapping("/freeze")
	public R freeze(@RequestBody Wallet wallet) {
		wallet.setUpdateTime(null);
		if(wallet.getFreezeNart() !=null && wallet.getFreezeNart().doubleValue()>=0){
			WalletChange walletChange = new WalletChange();

			walletChange.setOperateBy((long) SecurityUtils.getUser().getId());
			walletChange.setUserId(wallet.getUserId());
			walletChange.setNartValue(wallet.getFreezeNart());
			if (wallet.getFreezeNart().intValue() == 0) {
				Wallet walletById = walletService.getWalletById(wallet.getId());
				walletChange.setNartValue(walletById.getFreezeNart());
				walletChange.setSkuName("系统解冻");
			}else{
				walletChange.setSkuName("系统冻结");
			}
			walletChangeService.save(walletChange);

			return R.ok(walletService.updateById(wallet),"修改成功");
		} else if(wallet.getFreezeNart() !=null && wallet.getFreezeNart().doubleValue()<0){
			return R.failed("冻结值不能为负值");
		} else {
			return R.failed("冻结失败");
		}

	}
	/**
	 * 修改钱包表实名
	 * @param wallet 钱包表
	 * @return R
	 */
	@ApiOperation(value = "修改钱包表实名", notes = "修改钱包表实名")
	@SysLog("修改钱包表实名" )
	@PostMapping("/update_wallet")
	public R update_wallet(@RequestBody Wallet wallet) {
		wallet.setUpdateTime(null);
		return R.ok(walletService.updateById(wallet));

	}
	/**
	 * 修改钱包表
	 * @param changeVo 钱包表
	 * @return R
	 */
	@ApiOperation(value = "修改钱包表", notes = "修改钱包表")
	@SysLog("修改钱包表" )
	@PostMapping("/update_inner")
	@Inner
	public R updateByIdInner(@RequestBody WalletChangeVo changeVo) {
		return walletService.changeWallet(changeVo);
	}

	@NotNull


	/**
	 * 修改钱包表
	 * @param changeVo 钱包表
	 * @return R
	 */
	@ApiOperation(value = "钱包兑换功能(fromUserId 和toUserId是同一个,rmb和nice必须传值，并且相同，一个正一个负)", notes = "fromUserId 和toUserId是同一个,rmb和nice必须传值，并且相同，一个正一个负")
	@SysLog("钱包相互兑换" )
	@PostMapping("/change")
	public R change(@RequestBody WalletChangeVo changeVo) {
		WalletChange walletChange = new WalletChange();
		BeanUtil.copyProperties(changeVo , walletChange);
		walletChange.setOperateBy(changeVo.getFromUserId());
		walletChange.setUserId(changeVo.getToUserId());
		walletChangeService.save(walletChange);

		Wallet wallet = walletService.getBaseMapper().selectOne(Wrappers.<Wallet>lambdaQuery().eq(Wallet::getUserId, changeVo.getToUserId()));
		wallet.setRmbBalance(wallet.getRmbBalance().add(changeVo.getRmbValue()));
		wallet.setNartBalance(wallet.getNartBalance().add(changeVo.getNartValue()));
		return R.ok(walletService.updateById(wallet));
	}

	/**
	 * 通过id删除钱包表
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除钱包表", notes = "通过id删除钱包表")
	@SysLog("通过id删除钱包表" )
	@DeleteMapping("/{id}" )
	public R removeById(@PathVariable Long id) {
		return R.ok(walletService.removeById(id));
	}

	@ApiOperation(value = "同意钱包记录修改", notes = "同意钱包记录修改")
	@SysLog("同意钱包记录修改" )
	@PostMapping("/changeTypeToAgree")
	public R changeTypeToAgree(@RequestBody Wallet wallet) {
		WalletChange walletChange = new WalletChange();
		walletChange.setRmbValue(wallet.getNewRmbBalance());
		walletChange.setNartValue(wallet.getNewNartBalance());
		walletChange.setOperateBy(wallet.getOperateBy());
		walletChange.setUserId(wallet.getUserId());
		walletChange.setSkuName(wallet.getReason());
		walletChangeService.save(walletChange);
		wallet.setRmbBalance(wallet.getRmbBalance().add(wallet.getNewRmbBalance()));
		wallet.setNartBalance(wallet.getNartBalance().add(wallet.getNewNartBalance()));
		wallet.setNewNartBalance(BigDecimal.ZERO);
		wallet.setNewRmbBalance(BigDecimal.ZERO);
		wallet.setOperateBy(Long.parseLong("-1"));
		wallet.setType(1);
		return R.ok(walletService.updateById(wallet));
	}
	@ApiOperation(value = "拒绝钱包记录修改", notes = "拒绝钱包记录修改")
	@SysLog("拒绝钱包记录修改" )
	@PostMapping("/changeTypeToRefuse")
	public R changeTypeToRefuse(@RequestBody Wallet wallet) {
		wallet.setNewRmbBalance(BigDecimal.ZERO);
		wallet.setNewNartBalance(BigDecimal.ZERO);
		wallet.setOperateBy(Long.parseLong("-1"));
		wallet.setType(2);
		return R.ok(walletService.updateById(wallet));
	}

	/**
	 * @param userId
	 * @param from
	 * @return
	 */
	@Inner
	@GetMapping("/findWalletByUserId/{userId}")
	public Wallet findWalletByUserId(@PathVariable("userId") Long userId, @RequestHeader(SecurityConstants.FROM) String from) {
		Wallet w=walletService.findWalletByUserId(userId);
		return w;
	}

}
